<template>
  <div class="appointment-list">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>预约列表</span>
          <el-button type="primary" @click="handleAdd">新增预约</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="预约日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="培训科目">
          <el-select v-model="searchForm.subject" placeholder="选择科目" clearable>
            <el-option label="科目二" value="subject2" />
            <el-option label="科目三" value="subject3" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约状态">
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="学员姓名/手机号/教练姓名"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        v-loading="loading"
      >
        <el-table-column prop="id" label="预约编号" width="120" />
        <el-table-column prop="date" label="预约日期" width="120" />
        <el-table-column prop="time" label="预约时间" width="120" />
        <el-table-column prop="subject" label="培训科目" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.subject === 'subject2' ? 'success' : 'warning'"
              effect="plain"
            >
              {{ row.subject === 'subject2' ? '科目二' : '科目三' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="studentName" label="学员姓名" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="coachName" label="教练姓名" width="100" />
        <el-table-column prop="status" label="预约状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending'"
              type="success"
              size="small"
              @click="handleConfirm(row)"
            >确认</el-button>
            <el-button
              v-if="['pending', 'confirmed'].includes(row.status)"
              type="danger"
              size="small"
              @click="handleCancel(row)"
            >取消</el-button>
            <el-button
              v-if="row.status === 'confirmed'"
              type="primary"
              size="small"
              @click="handleComplete(row)"
            >完成</el-button>
            <el-button
              type="info"
              size="small"
              @click="handleView(row)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 查看详情对话框 -->
      <el-dialog
        v-model="detailDialogVisible"
        title="预约详情"
        width="600px"
      >
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预约编号">{{ selectedRow?.id }}</el-descriptions-item>
          <el-descriptions-item label="预约状态">
            <el-tag :type="getStatusType(selectedRow?.status)">
              {{ getStatusText(selectedRow?.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">{{ selectedRow?.date }}</el-descriptions-item>
          <el-descriptions-item label="预约时间">{{ selectedRow?.time }}</el-descriptions-item>
          <el-descriptions-item label="培训科目">
            {{ selectedRow?.subject === 'subject2' ? '科目二' : '科目三' }}
          </el-descriptions-item>
          <el-descriptions-item label="学员姓名">{{ selectedRow?.studentName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedRow?.phone }}</el-descriptions-item>
          <el-descriptions-item label="教练姓名">{{ selectedRow?.coachName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ selectedRow?.createTime }}</el-descriptions-item>
          <el-descriptions-item label="备注信息" :span="2">{{ selectedRow?.remark }}</el-descriptions-item>
        </el-descriptions>
      </el-dialog>

      <!-- 新增预约抽屉 -->
      <el-drawer
        title="新增预约"
        v-model="addDrawerVisible"
        direction="rtl"
        size="50%"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="预约日期" prop="date">
            <el-date-picker
              v-model="form.date"
              type="date"
              placeholder="选择日期"
              :disabled-date="disabledDate"
            />
          </el-form-item>
          <el-form-item label="预约时间" prop="time">
            <el-select v-model="form.time" placeholder="选择时间">
              <el-option
                v-for="time in availableTimes"
                :key="time"
                :label="time"
                :value="time"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="培训科目" prop="subject">
            <el-select v-model="form.subject" placeholder="选择科目">
              <el-option label="科目二" value="subject2" />
              <el-option label="科目三" value="subject3" />
            </el-select>
          </el-form-item>
          <el-form-item label="学员" prop="studentId">
            <el-select
              v-model="form.studentId"
              placeholder="选择学员"
              filterable
              remote
              :remote-method="searchStudents"
              :loading="studentLoading"
            >
              <el-option
                v-for="student in students"
                :key="student.id"
                :label="student.name"
                :value="student.id"
              >
                <span>{{ student.name }}</span>
                <span class="student-info">{{ student.phone }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教练" prop="coachId">
            <el-select
              v-model="form.coachId"
              placeholder="选择教练"
              filterable
            >
              <el-option
                v-for="coach in coaches"
                :key="coach.id"
                :label="coach.name"
                :value="coach.id"
              >
                <span>{{ coach.name }}</span>
                <span class="coach-info">{{ getCoachTypeText(coach.type) }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addDrawerVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = ref({
  dateRange: [],
  subject: '',
  status: '',
  keyword: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([
  {
    id: 'AP202403150001',
    date: '2024-03-15',
    time: '09:00-11:00',
    subject: 'subject2',
    studentName: '张三',
    phone: '13800138000',
    coachName: '李教练',
    status: 'confirmed',
    createTime: '2024-03-14 15:30:00',
    remark: '倒车入库训练'
  },
  {
    id: 'AP202403150002',
    date: '2024-03-15',
    time: '14:00-16:00',
    subject: 'subject2',
    studentName: '李四',
    phone: '13800138001',
    coachName: '李教练',
    status: 'pending',
    createTime: '2024-03-14 16:00:00',
    remark: '侧方停车训练'
  },
  {
    id: 'AP202403150003',
    date: '2024-03-15',
    time: '16:00-18:00',
    subject: 'subject3',
    studentName: '王五',
    phone: '13800138002',
    coachName: '王教练',
    status: 'completed',
    createTime: '2024-03-14 16:30:00',
    remark: '变更车道训练'
  },
  {
    id: 'AP202403160001',
    date: '2024-03-16',
    time: '09:00-11:00',
    subject: 'subject2',
    studentName: '赵六',
    phone: '13800138003',
    coachName: '张教练',
    status: 'cancelled',
    createTime: '2024-03-14 17:00:00',
    remark: '学员临时有事取消'
  },
  {
    id: 'AP202403160002',
    date: '2024-03-16',
    time: '14:00-16:00',
    subject: 'subject3',
    studentName: '孙七',
    phone: '13800138004',
    coachName: '王教练',
    status: 'confirmed',
    createTime: '2024-03-14 17:30:00',
    remark: '路口转弯训练'
  }
])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 详情对话框
const detailDialogVisible = ref(false)
const selectedRow = ref(null)

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'confirmed': 'success',
    'completed': 'info',
    'cancelled': 'danger'
  }
  return typeMap[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return textMap[status] || status
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    dateRange: [],
    subject: '',
    status: '',
    keyword: ''
  }
  handleSearch()
}

// 新增预约抽屉相关
const addDrawerVisible = ref(false)
const formRef = ref(null)
const form = ref({
  date: '',
  time: '',
  subject: '',
  studentId: '',
  coachId: '',
  remark: ''
})
const rules = ref({
  date: [{ required: true, message: '请选择预约日期', trigger: 'blur' }],
  time: [{ required: true, message: '请选择预约时间', trigger: 'blur' }],
  subject: [{ required: true, message: '请选择培训科目', trigger: 'blur' }],
  studentId: [{ required: true, message: '请选择学员', trigger: 'blur' }],
  coachId: [{ required: true, message: '请选择教练', trigger: 'blur' }]
})
const availableTimes = [
  '08:00-10:00',
  '10:00-12:00',
  '14:00-16:00',
  '16:00-18:00',
  '19:00-21:00'
]
const students = ref([])
const studentLoading = ref(false)
const coaches = ref([
  { id: '1', name: '李教练', type: 'subject2' },
  { id: '2', name: '王教练', type: 'subject3' },
  { id: '3', name: '张教练', type: 'subject2' },
  { id: '4', name: '刘教练', type: 'subject3' },
  { id: '5', name: '陈教练', type: 'subject2' }
])

// 新增
const handleAdd = () => {
  addDrawerVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 模拟提交逻辑
      ElMessage.success('预约添加成功')
      addDrawerVisible.value = false
      // 重置表单
      form.value = {
        date: '',
        time: '',
        subject: '',
        studentId: '',
        coachId: '',
        remark: ''
      }
      // 刷新数据
      fetchData()
    }
  })
}

// 搜索学员
const searchStudents = (query) => {
  studentLoading.value = true
  // 模拟搜索接口
  setTimeout(() => {
    // 这里应该是根据query过滤学员
    students.value = [
      { id: '1', name: '张三', phone: '13800138000' },
      { id: '2', name: '李四', phone: '13800138001' },
      { id: '3', name: '王五', phone: '13800138002' }
    ]
    studentLoading.value = false
  }, 500)
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 获取教练类型文本
const getCoachTypeText = (type) => {
  return type === 'subject2' ? '科目二' : '科目三'
}

// 确认预约
const handleConfirm = (row) => {
  ElMessageBox.confirm(
    '确认该预约吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现确认逻辑
    ElMessage.success('预约已确认')
  }).catch(() => {})
}

// 取消预约
const handleCancel = (row) => {
  ElMessageBox.confirm(
    '确认取消该预约吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现取消逻辑
    ElMessage.success('预约已取消')
  }).catch(() => {})
}

// 完成培训
const handleComplete = (row) => {
  ElMessageBox.confirm(
    '确认完成培训吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 实现完成逻辑
    ElMessage.success('培训已完成')
  }).catch(() => {})
}

// 查看详情
const handleView = (row) => {
  selectedRow.value = row
  detailDialogVisible.value = true
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 获取数据
const fetchData = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    total.value = tableData.value.length
    loading.value = false
  }, 500)
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.appointment-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.student-info,
.coach-info {
  color: #888;
  font-size: 12px;
  margin-left: 10px;
}

dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>